import { Context, Next } from 'koa';
import { KoaMiddlewareInterface } from 'routing-controllers';
import { checkCarry, checkScheme, checkValid } from '../utils/auth';
import { message } from '../utils/result';

/**
 * 局部中间件
 */
export class AuthMiddleware implements KoaMiddlewareInterface {
  async use(context: Context, next: Next): Promise<any> {
    const carry = checkCarry(context);
    if (!carry.pass) {
      context.body = message(401, carry.message);
      return;
    }
    const scheme = checkScheme(carry.credential!);
    if (!scheme.pass) {
      context.body = message(401, scheme.message);
      return;
    }
    const valid = checkValid(scheme.credential!);
    if (!valid.pass) {
      context.body = message(401, valid.message);
      return;
    }
    // const token = context.cookies.get('authorization') || request.header['authorization'];
    // console.log(token);
    await next();
  }
}

export class LoggerMiddleware implements KoaMiddlewareInterface {
  async use(context: Context, next: Next): Promise<any> {
    await next();
  }
}
